我的模型 Price
具有以下范围和属性。
def self.total
self.sum(:amount) + self.sum(:tax)
end
def self.today
where(:date => Date.today)
end
def self.for_data
where(:bought => true)
end
我有获取当前用户今天总量的作用域链。
<p class="today">
Today
<span class="amount today">
<%= number_to_currency(current_user.prices.for_data.today.total) %>
</span>
</p>
我写了一个规范来测试这个。
# user_pages_spec
describe 'Overview Page' do
it 'shows spending' do
make_user_and_login
price = FactoryGirl.create(:price)
click_link('Overview')
page.should have_selector('title', :text => 'Overview')
within('p.today', :text => 'Today') do
page.should have_content('$1.01')
end
end
end
这是我的价格工厂:
factory :price do
amount '1.00'
tax '0.01'
bought true
date Date.today
end
不幸的是,这会返回错误:
1) UserPages Account Settings Data Page shows spending
Failure/Error: page.should have_content('$1.01')
expected there to be content "$1.01" in "\n\t\t\tToday\n\t\t\t$0.00\n\t\t"
在 View 中手动放置 $1.01
是可行的,但当我依赖范围时则不行。看起来它没有检测工厂或一般范围,因为它返回 $0.00
。为什么以及如何解决这个问题?
谢谢。
支持/user_macros.rb
module UserMacros
def make_user_and_login
user = FactoryGirl.create(:user)
visit new_user_session_path
page.should have_selector('title', :text => 'Login')
fill_in('Email', :with => user.email)
fill_in('Password', :with => user.password)
click_button('Login')
page.should have_selector('title', :text => 'Home')
end
end
最佳答案
我认为问题是价格记录与 current_user 没有关系。所以在这种情况下,current_user total 实际上是 0.00。您可以通过像这样更改价格工厂来解决这个问题:
factory :price do
amount '1.00'
tax '0.01'
bought true
date Date.today
user { User.first || FactoryGirl.create(:user) }
end
关于ruby - Capybara 和 Rspec 没有范围界定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486780/