2013-01-09 87 views
0

是否可以在rspec中测试复数函数?Rails rspec factorygirl复数测试

let(:schedule) { FactoryGirl.create(:schedule) } 

Failure/Error: it { should have_selector('h1', text: pluralize(Schedule.count.to_s, "schedule")) } 
NoMethodError: 
    undefined method `pluralize' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0xb607068c> 

答:(为指出由以下埃里克·C)

describe SchedulesHelper do 
    describe "pluralize schedule" do 
    if(Schedule.count > 0) 
     it { pluralize(1, "schedule").should == "1 schedule" } 
    else 
     it { pluralize(0, "schedule").should == "0 schedules" } 
    end  
    end 
end 
+0

您似乎没有测试复数方法。您似乎在测试是否存在某个html,并且您正在使用pluralize方法来帮助您。你问是否可以用复数方法测试? –

+0

是的。是否有可能测试'pluralize'? – janejanejane

回答

1

回答你的问题是...那种。 Rails提供了使用复数和使用rspec-rails的功能,假设您正在使用这些功能,您可以根据需要调用rails方法。如果这是一个观点的测试,这是有点什么样子,你可以输入类似:

it { should have_selector('h1', text: view.pluralize(Schedule.count.to_s, "schedule")) } 

这里的关键是,你要添加的视图。复数之前的

我想强调的是,在测试时,在看起来是视图测试的内部测试助手方法并不是一个好主意。如果你真的想自己测试复数形式,最好在助手规范中测试它。做这样的事:

it { pluralize(1, "schedule").should == "1 schedule" } 
it { pluralize(0, "schedule").should == "0 schedules" } 

这样,你可以放心的结果,并在其他测试做出假设,然后测试正确的结果。它实际上将不可避免地使测试更好,因为如果像复数形式这样的助手发生变化,那么你有两个测试可以警告这种变化。然后你可以相应地调整。只是一个想法。

+0

好的。谢谢埃里克。我现在已经在我的帮手规范中进行了复数测试。 :) – janejanejane

5

我是新的回报率和RSpec,我有类似的错误是开始这个​​线程的队友:

失败:

1) Static Pages Home Page for signed-in users should show the total feeds 
Failure/Error: expect(page).to have_content(pluralize(user.feed.count, 'micropost')) 
NoMethodError: 
    undefined method `pluralize' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_2:0x007fade8f35938> 
    # ./spec/requests/static_pages_spec.rb:39:in `block (4 levels) in <top (required)>' 

我试过view.pluralize没有运气。 ..我终于在我的集成测试中使用这个:

it "should show the total feeds" do 
    expect(page).to have_content("micropost".pluralize(user.feed.count))     
end 

和我的测试很好地工作。

希望这可以帮助别人。

iVieL。

+1

谢谢!这帮了我很多。 我建议你可以通过针对特定元素 'expect(page).to have_selector(“section span”,text:“micropost”.pluralize(user.feed.count))来改进它。 – claw68